import React, { useEffect, useState, useMemo, useRef, useReducer, useCallback } from "react";
import { pdfSignTask_query_page } from "src/api/home";
import { getPdfInfo } from "src/api/pqsstartWkInfo";
import { getSealsInfo, signAutoPdf } from "src/api/signTask";
import { NavBar, Tabs, List, Space, Empty, Popup, Radio, Button } from "antd-mobile";
import { SearchOutline } from "antd-mobile-icons";
import BetterScroll from "pages/components/betterScroll";
import Btns from "pages/components/btns";
import { API_URL, PDF_URL } from "src/config";
import { DBNAME, BEAN_NAME } from "./sign-config";
import { PreviewPdf, isNormalBrowser } from "src/utils/index";
import "./index.scss";
import { historyShape, storeShape, locationShape } from "src/propType";
import Toast from "src/pages/components/clickableToast";

const limit = 15;

function listReducer(state, action) {
    switch (action.type) {
        case "activity_key": {
            return {
                ...state,
                activityKey: action.activityKey,
            };
        }
        case "task_list": {
            return {
                ...state,
                todoList: action.todoList,
                loading: action.loading,
                total: action.total,
                page: action.page,
            };
        }
        case "done_list": {
            return {
                ...state,
                doneList: action.doneList,
                loading: action.loading,
                total: action.total,
                page: action.page,
            };
        }
        case "before_add": {
            return {
                ...state,
                loading: true,
            };
        }
    }
}

const initialList = {
    todoList: [],
    doneList: [],
    loading: true,
    page: 1,
    limit,
    total: 0,
    activityKey: "0",
};

const tenantType = 2,
    tenantNo = "350794";

const SignTask = props => {
    const [list, setList] = useReducer(listReducer, initialList);
    const currentList = useStateRef(list);
    const [selectTable, setSelectTable] = useState(null);
    const [visible, setVisible] = useState(false);

    const [userCertInfoList, setUserCertInfoList] = useState([]);

    const [userCertInfoValue, setUerCertInfoValue] = useState(null);

    const { store, location, history } = props;
    const user = store.user.userData;

    const getList = (cb, restPage) => {
        let { page, todoList, doneList, activityKey } = currentList.current;
        page = restPage ? 1 : page;
        const beanName = BEAN_NAME + "-" + user.projId;
        const isCurDay = activityKey === "0" ? null : 1;
        Toast.show({
            icon: "loading",
            content: "加载中…",
        });
        pdfSignTask_query_page(page, limit, beanName, DBNAME, isCurDay).then(res => {
            const { code, data, total, msg } = res;
            if (code === 200) {
                const tableData = data?.map(function (item, i) {
                    item.tableName = item.tableName || item.name;
                    item.cdate = item.cdate && item.cdate.substring(0, 10);
                    if (item.tableName && item.name) {
                        item.names = item.tableName.split(item.name);
                        item.tName = item.names && item.names[0];
                        item.signTableName = item.name || item.tableName;
                        item.isSelected = false;
                    }
                    return item;
                });
                if (activityKey === "0") {
                    setList({
                        type: "task_list",
                        todoList: restPage ? tableData : [...todoList, ...tableData],
                        loading: false,
                        total,
                        page: ++page,
                    });
                } else {
                    setList({
                        type: "done_list",
                        doneList: restPage ? tableData : [...doneList, ...tableData],
                        loading: false,
                        total,
                        page: ++page,
                    });
                }
            } else {
                Toast.show({
                    icon: "fail",
                    content: msg,
                });
            }
            cb && cb();
        });
    };

    const refreshList = () => {
        getList(null, true);
    };

    const toViewPdf = async record => {
        record.datakid = "1";
        let kid = record && (record.kid || record.recordId);
        if (!isNormalBrowser()) {
            const url = `${API_URL}/wpfile/downloadPdf?dbName=GPMSPQS&recordId=${kid}&title=${
                record.moduleName || ""
            }.pdf`;
            PreviewPdf(url);
            return;
        }
        const res = await getPdfInfo(kid);
        const { data, msg } = res;
        if (res.success && data && Object.keys(data).length) {
            const fileUrl = data && (data.pdfName || data.pdfPath || data.svrFullPath);
            const url = (PDF_URL + fileUrl).replace(/\\/g, "/");
            window.open(url);
        } else {
            Toast.show({
                icon: "fail",
                content: msg,
                afterClose: () => {},
            });
            return;
        }
    };

    useEffect(() => {
        refreshList();
    }, [list.activityKey]);

    const changeTab = activityKey => {
        setList({
            type: "activity_key",
            activityKey,
        });
    };

    //上拉加载
    const pullingUp = useCallback(() => {
        let { page, limit, total } = currentList.current;
        if (page > Math.ceil(total / limit)) {
            Toast.show({
                content: "没有更多数据了!",
            });
            return;
        }
        getList();
    }, [list]);

    // 获取图章信息列表（单个或多个列表）
    const getAllCertList = async () => {
        try {
            const res = await getSealsInfo({ tenantType, tenantNo });
            if (res.code === 200) {
                let sealList = res.data.sealList;
                let _userCertInfoList = [];
                for (let i = 0; i < sealList.length; i++) {
                    if (sealList[i].sealType === "个人章(手写签名)") {
                        sealList[i].certId = tenantNo;
                        sealList[i].sealUrl = "data:image/png;base64," + sealList[i].sealImage;
                        _userCertInfoList.push(sealList[i]);
                    }
                }
                setUserCertInfoList(_userCertInfoList);
            }
        } catch (error) {
            console.log(error);
        }
    };

    const signConfirm = async () => {
        if (!userCertInfoValue) {
            Toast.show({
                content: "请选择签名!",
            });
            return;
        }
        const certInfo = userCertInfoList.find(one => one.sealCode === userCertInfoValue);
        try {
            if (!certInfo) return;
            const res = await signAutoPdf({
                certId: certInfo.certId, //暂时写死，等正式使用再去掉
                signsKid: selectTable.signsKid,
                sealName: certInfo.sealName,
            });
            if (res.success && res.data) {
                Toast.show({
                    icon: "success",
                    content: "签署成功！",
                });
                setVisible(false);
                setSelectTable(null);
                refreshList();
            }
        } catch (error) {
            Toast.show({
                icon: "fail",
                content: error,
            });
        }
    };

    const currenTabList = useMemo(() => {
        return list.activityKey === "0" ? list.todoList : list.doneList;
    }, [list]);

    const hasData = currenTabList?.length;

    const right = (
        <div style={{ fontSize: 24 }}>
            <Space style={{ "--gap": "16px" }}>
                <SearchOutline />
            </Space>
        </div>
    );

    const btns = [
        {
            label: "签署",
            key: "0",
            fn: table => {
                setVisible(true);
                setSelectTable(table);
                getAllCertList();
            },
            hidden: list.activityKey === "1",
        },
        {
            label: "查看",
            key: "1",
            fn: table => toViewPdf(table),
        },
    ];

    return (
        <div className="sign-list">
            <NavBar back="返回" onBack={() => props.history.go(-1)}>
                签名管理
            </NavBar>
            <Tabs activeKey={list.activityKey} onChange={changeTab}>
                <Tabs.Tab title="未签名列表" key="0" />
                <Tabs.Tab title="已签名列表" key="1" />
            </Tabs>
            <div className="scroll-container">
                <BetterScroll pullingUp={pullingUp}>
                    <div className={`${hasData ? "sign-list-container" : "empty"}`}>
                        {hasData ? (
                            currenTabList.map(table => {
                                const { signsKid, tableName, code, cdate, userName } = table;
                                return (
                                    <div className="list-container" key={signsKid}>
                                        <List.Item
                                            arrowIcon={false}
                                            clickable={false}
                                            onClick={e => {}}
                                        >
                                            <div className="content">
                                                <p>
                                                    <span>签名表格名称：</span>
                                                    <span>{tableName}</span>
                                                </p>
                                                <p>
                                                    <span>PDF(编号/名称)：</span>
                                                    <span>{code}</span>
                                                </p>
                                                <p>
                                                    <span>审核日期：</span>
                                                    <span>{cdate}</span>
                                                </p>
                                                <p>
                                                    <span>审核人：</span>
                                                    <span>{userName}</span>
                                                </p>
                                                <p>
                                                    <span>审核状态：</span>
                                                    <span
                                                        className={`${
                                                            list.activityKey === "0"
                                                                ? "orange"
                                                                : "green"
                                                        }`}
                                                    >
                                                        {list.activityKey === "0"
                                                            ? "待审核"
                                                            : "已审核"}
                                                    </span>
                                                </p>
                                                <p>
                                                    <span>附件：</span>
                                                    <span
                                                        className="blue"
                                                        onClick={() =>
                                                            props.history.push(
                                                                `/FileInfo?${table.recordId}`,
                                                            )
                                                        }
                                                    >
                                                        查看附件
                                                    </span>
                                                </p>
                                            </div>
                                            <Btns source={table} btns={btns} />
                                        </List.Item>
                                    </div>
                                );
                            })
                        ) : (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        )}
                    </div>
                </BetterScroll>
            </div>
            <Popup
                visible={visible}
                onMaskClick={() => {
                    setVisible(false);
                }}
                onClose={() => {
                    setVisible(false);
                }}
                bodyStyle={{ height: "60vh" }}
                getContainer={null}
                showCloseButton={true}
                className="sign-config-list"
            >
                <h2 className="title">选择签名并签署</h2>
                <div className="list">
                    {userCertInfoList.length > 0 ? (
                        <Radio.Group
                            value={userCertInfoValue}
                            onChange={value => {
                                setUerCertInfoValue(value);
                            }}
                        >
                            {userCertInfoList?.map(info => {
                                const { sealCode } = info;
                                return (
                                    <div className="list-item" key={sealCode}>
                                        <Radio value={sealCode}>
                                            <div className="message">
                                                {sealCode}(状态: {info.sealStatus})
                                            </div>
                                            <img src={info.sealUrl} alt="" />
                                        </Radio>
                                    </div>
                                );
                            })}
                        </Radio.Group>
                    ) : (
                        <div>当前用户未配置图章信息</div>
                    )}
                </div>
                <div className="operate">
                    <Button block size="large" onClick={() => setVisible(false)}>
                        取消
                    </Button>
                    <Button block size="large" color="primary" onClick={() => signConfirm()}>
                        签名
                    </Button>
                </div>
            </Popup>
        </div>
    );
};

export function useStateRef(state) {
    const stateRef = useRef();
    useEffect(() => {
        stateRef.current = state;
        return () => {};
    }, [state]);
    return stateRef;
}

SignTask.propTypes = {
    store: storeShape,
    history: historyShape,
    location: locationShape,
};

export default SignTask;
